
// <copyright file="DefaultDataRecordComparer.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   Description of DefaultRecordComparer.
// </summary>


#region Header

/*
 * Created by SharpDevelop.
 * User: blrsos
 * Date: 7/20/2011
 * Time: 10:34 AM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
#endregion Header

namespace SubhadraSolutions.Sharp.Utils.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;

    /// <summary>
    ///     Description of DefaultRecordComparer.
    /// </summary>
    public sealed class DefaultDataRecordComparer : IComparer<IDataRecord>
    {
        #region Fields

        /// <summary>
        /// The key column names.
        /// </summary>
        private readonly List<string> _keyColumnNames;

        #endregion Fields

        #region Constructors and Finalizers

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultDataRecordComparer"/> class.
        /// </summary>
        /// <param name="keyColumnNames">
        /// The key column names.
        /// </param>
        public DefaultDataRecordComparer(IEnumerable<string> keyColumnNames)
        {
            this._keyColumnNames = new List<string>(keyColumnNames);
        }

        #endregion Constructors and Finalizers

        #region Public Methods and Operators

        /// <summary>
        /// The compare.
        /// </summary>
        /// <param name="record1">
        /// The record 1.
        /// </param>
        /// <param name="record2">
        /// The record 2.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        public int Compare(IDataRecord record1, IDataRecord record2)
        {
            foreach (string keyColumnName in this._keyColumnNames)
            {
                var c1 = record1[keyColumnName] as IComparable;
                var c2 = record2[keyColumnName] as IComparable;
                if (c1 != null && c2 != null)
                {
                    int cResult = c1.CompareTo(c2);
                    if (cResult != 0)
                    {
                        return cResult;
                    }
                }
                else
                {
                    if (c2 == null && c1 == null)
                    {
                        continue;
                    }

                    return c1 == null ? 1 : -1;
                }
            }

            return 0;
        }

        #endregion Public Methods and Operators
    }
}